<template>
	<view class="">
		<view class="spliceLine">
		</view>
		<view class="writeInfo-contaienr">
			<view class="wreteInfo-body">
				<input type="text" v-model="publishForm.title" class="wreteInfo" placeholder="项目名称">
			</view>
			<!-- 写一个项目简介 -->
			<!-- <view class="writeIntro-body">
				<textarea v-model="publishForm.content" placeholder="项目简介" class="writeIntro"
					:style="{ 'height': '150px', 'overflow-y': 'hidden' }"></textarea>
			</view> -->
			<view class="writeDetail-body">
				<!-- <textarea v-model="detail" placeholder="项目详情" class="writeDetail"
					:style="{ 'height': '150px', 'overflow-y': 'hidden'}"></textarea> -->
				<view class="richtext">
					<piaoyiEditor :values="values" :maxlength="3000" @changes="saveContens" :readOnly="readOnly"
						:photoUrl="photoUrl" :api="api" :name="name" />
					<Attachment mode="create" :canUploadFile="true" :uploadFileUrl="uploadUrl" @uploadSuccess="uploadSuccess"
						:header="header" :showProcess="true" :attachmentList.sync="attachmentList"></Attachment>
				</view>
			</view>
			<view class="wreteInfo-body">
				<input type="text" v-model="keywordsInput" @input="handleInput" class="wreteInfo" placeholder="请填写项目关键字以“,”分隔">
			</view>
			<!-- <view class="price">
				<view class="price-title">
					<text>设为热门</text>
				</view>
				<view class="price-body">
					<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
				</view>
			</view> -->
			<view class="price">
				<view class="price-title">
					<text>你的城市</text>
				</view>
				<view class="price-body">
					<input type="text" v-model="publishForm.city" class="price-input" placeholder="城市">
				</view>
			</view>

			<view class="price">
				<view class="price-title">
					<text>项目预算</text>
				</view>
				<view class="price-body">
					<input type="number" v-model="publishForm.price" @input="priceInput" class="price-input" placeholder="项目预算（元）"
						inputmode="numeric" pattern="[0-9]*">
				</view>
			</view>

			<!-- 底部发布按钮 -->
			<view class="publish-btn">
				<button @tap="publishBtn" ref="formButton" class="cu-btn round bg-blue xl"
					style="width:200px;height:70px;font-size:46rpx">立即发布</button>
			</view>
		</view>
	</view>
</template>

<script>
import piaoyiEditor from '@/uni_modules/piaoyi-editor/components/piaoyi-editor/piaoyi-editor.vue';
import Attachment from '../../components/jin-attachment/jin-attachment.vue';

export default {
	data() {
		return {
			ImagesList: '',
			filesList: '',
			switchA: false,
			attachmentList: [],
			header: {
				'token': ''
			},
			uploadUrl: 'https://kehu.ruoyiweb.hellomky.cn/' + this.$myHttp.urlMap.uploadFiles,
			filePath: '', // 存放选择的文件路径
			fileName: '', // 存放选择的文件名
			fileIconUrl: '', // 存放选择的文件图标 URL
			publishForm: {
				title: '',
				intro: '',
				detail: '',
				keywords: '',
				price: null,
				city: '',
				imgList: [],
				state: 1,
			},
			finalKeywords: '',
			keywordsInput: '',
			readOnly: false, //是否只读
			photoUrl: 'https://kehu.ruoyiweb.hellomky.cn/', //服务器图片域名或者ip
			api: 'api/common/upload', //上传图片接口地址
			txt: '',
			name: 'file',
			values: '',
			form: {
				desc: '',
			},
			inputValue: '',
			intro: '',
			detail: '',
			imgList: []
		};
	},
	components: {
		piaoyiEditor,
		Attachment
	},
	onLoad(options) {
		let token = JSON.parse(uni.getStorageSync('vuexvuex'))
		var parsedData = JSON.parse(token.value);
		var tokenValue = parsedData.userinfo.token;
		console.log('tokenValue: ', tokenValue)
		this.header['token'] = tokenValue
	},
	methods: {
		priceInput() {
			// 过滤非数字字符
			this.publishForm.price = this.publishForm.price.replace(/[^0-9]/g, '');
		},
		SwitchA(e) {
			this.switchA = e.detail.value
		},
		uploadSuccess(result) {
			const fileUrl = JSON.parse(result.data)

			// 获取文件扩展名
			const fileExtension = fileUrl.data.url.split(".").pop().toLowerCase();
			console.log('fileExtension: ', fileExtension)

			// 根据扩展名判断文件类型
			if (fileExtension === "jpg" || fileExtension === "jpeg" || fileExtension === "png" || fileExtension === "gif") {
				// 这是一个图片文件

				// 将图片 URL 存放到图片变量中
				if (this.ImagesList) {
					// 如果 this.ImagesList 不为空，则添加逗号
					this.ImagesList += ',';
				}

				this.ImagesList += fileUrl.data.url;



			} else {
				// 这是其他类型的文件

				// 将文件 URL 存放到附件变量中
				if (this.filesList) {
					// 如果 this.ImagesList 不为空，则添加逗号
					this.filesList += ',';
				}

				this.filesList += fileUrl.data.url;


			}
			if (result.statusCode == 200) {
				//上传成功的回调处理
				uni.showToast({
					title: '上传成功',
					icon: 'none'
				});
			} else {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				});
			}
		},
		async publishBtn() {
			
			if (this.publishForm.title == '') {
				uni.showToast({
					title: '请填写项目名称！',
					icon: 'none'
				});

			} else if (this.txt == '') {
				uni.showToast({
					title: '请填写项目详情！',
					icon: 'none'
				});
			} else if (this.publishForm.price == '') {
				uni.showToast({
					title: '请填写项目价格！',
					icon: 'none'
				});
			} else {
				// 使用 filter 方法筛选出 type 为 "image" 的元素
				// const imageElements = this.attachmentList.filter(item => item.type === "image");
				// const attachElements = this.attachmentList.filter(item => item.type === "file");

				// 使用 map 方法将 url 属性组成一个字符串
				// const imageUrlsString = imageElements.map(item => item.url).join(',');
				// const filesString = attachElements.map(item => item.url).join(',');


				if (this.publishForm.keywords !== '') {
					this.finalKeywords = this.publishForm.keywords.join(",");
				}
				
				
				let res = await this.$myHttp.post({

					url: this.$myHttp.urlMap.publishProject,
					data: {
						name: this.publishForm.title,
						content: encodeURIComponent(this.txt),
						price: this.publishForm.price,
						keywords: this.finalKeywords,
						city: this.publishForm.city,
						images: this.ImagesList,
						attachfile: this.filesList,
					}
				})
				if (res.code == 1) {
					uni.showToast({
						title: '发布成功',
						icon: 'success', // 图标，可选值：success/loading/none
						duration: 2000, // 提示框显示时间，单位为毫秒
						mask: true, // 是否显示透明蒙层，防止触摸穿透
						success: function () {
							// showToast 完成后执行跳转
							setTimeout(function () {
								uni.redirectTo({
									url: '/pages/projectEmploy/projectEmploy', // 替换成你的目标页面路径
								});
							}, 1000);
						},
					});

				}
			}

		},
		handleInput() {
			// 将输入框中的字符串按逗号分隔
			this.publishForm.keywords = this.keywordsInput.split(',');


		},

		DelImg(e) {
			uni.showModal({
				title: '提示',
				content: '确定要删除这张图片吗？',
				cancelText: '取消',
				confirmText: '确定',
				success: res => {
					if (res.confirm) {
						this.imgList.splice(e.currentTarget.dataset.index, 1)
					}
				}
			})
		},

		//监听富文本内容改变
		editorChange(e) {
			this.form.desc = e
		},
		saveContens(e) {

			this.txt = e.html
		},
		ViewImage(e) {
			uni.previewImage({
				urls: this.imgList,
				current: e.currentTarget.dataset.url
			});
		},
		ChooseImage() {
			uni.chooseImage({
				count: 4, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有

				sourceType: ['album'], //从相册选择
				success: (res) => {

					if (this.imgList.length != 0) {
						this.imgList = this.imgList.concat(res.tempFilePaths)

					} else {
						this.imgList = res.tempFilePaths

					}
				}
			});
		},
	}
}
</script>

<style lang="scss" scoped>
.uploadFile-container {
	display: flex;
	align-items: flex-start;
}

.writeInfo-contaienr {
	background-color: #fff;
	padding: 0rpx 40rpx;

	.publish-btn {
		display: flex;
		margin-top: 20rpx;
		padding-bottom: 20rpx;
		width: 100%;
		align-items: center;
		justify-content: center;
	}

	.price {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.price-title {
			text-align: left;
			text-indent: 20rpx;
			font-size: 30rpx;
			color: #333333;
		}

		.price-body {
			display: flex;
			align-items: center;
			height: 100rpx;
			border-bottom: 1px solid #F4F4F4;
			text-align: left;
			text-indent: 20rpx;
			font-size: 30rpx;
			color: #333333;

			.danwei {
				font-size: 30rpx;
				color: #333333;
				height: 100%;

			}

			.price-input {
				height: 100%;
				border: none;
				outline: none;
				font-size: 30rpx;
				color: #333333;
			}
		}
	}

	.writeDetail-body {
		display: flex;
		align-items: flex-start;
		border-bottom: 1px solid #F4F4F4;

		.writeDetail {
			width: 100%;
			height: 100%;
			padding: 20rpx;
			border-bottom: 1px solid #F4F4F4;
			outline: none;
		}
	}

	.writeIntro-body {
		display: flex;
		align-items: flex-start;

		.writeIntro {
			width: 100%;
			height: 100%;
			padding: 20rpx;
			border-bottom: 1px solid #F4F4F4;
			outline: none;
		}
	}

	.wreteInfo-body {
		display: flex;
		align-items: flex-start;

		.wreteInfo {
			width: 100%;
			height: 100%;
			padding: 20rpx;
			border-bottom: 1px solid #F4F4F4;
			outline: none;
		}
	}

}

.spliceLine {
	width: 100%;
	height: 6px;
	background-color: #EFEFEF;
}
</style>